<template>
    <div class="manage-index">
        <el-form :inline="true" :model="params">
            <el-form-item label="设备编码">
                <el-input v-model="params.deviceNo" placeholder="请输入设备编码"></el-input>
            </el-form-item>
            <el-form-item label="设备名称">
                <el-input v-model="params.deviceName" placeholder="请输入设备名称"></el-input>
            </el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
            <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
        </el-form>

        <el-button type="danger" plain :icon="Delete" @click="Delete1">清空</el-button>

        <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="deviceNo" label="设备编码" width="120"></el-table-column>
            <el-table-column prop="deviceName" label="设备名称" width="120"></el-table-column>
            <el-table-column prop="brand" label="品牌" width="120"></el-table-column>
            <el-table-column prop="specificationModel" label="规格型号" width="120"></el-table-column>
            <el-table-column prop="workshop.workshopName" label="所属车间" width="120"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="120"></el-table-column>
            <el-table-column prop="deviceStatus" label="状态" width="120"></el-table-column>

            <el-table-column label="操作" width="300px">
                <template #default="scope">
                    <el-button type="danger" link @click="Delete2(scope.row)" :icon="Delete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination
                        v-model:current-page="params.currentPage"
                        v-model:page-size="params.pageSize"
                        background
                        :default-page-size="params.pageSize"
                        :page-sizes="pageSizes"
                        layout="total,sizes,prev,pager,next,jumper"
                        :total="pageResult.total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>
        <!-- 分页组件结束 -->

        <!-- 新增或修改弹窗 -->
        <el-dialog v-model="visible" :title="title" width="700" @close="handleClose">
            <el-form :model="form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="设备编码">
                            <el-input v-model="form.deviceNo" placeholder="请输入设备编码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备名称">
                            <el-input v-model="form.deviceName" placeholder="请输入设备名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="品牌">
                            <el-input v-model="form.brand" placeholder="请输入品牌"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备分类">
                            <el-select v-model="form.deviceTypeId" placeholder="请选择设备分类">
                                <el-option
                                    v-for="category in deviceCategories"
                                    :key="category.deviceTypeNo"
                                    :label="category.deviceTypeName"
                                    :value="category.deviceTypeNo" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="规格型号">
                            <el-input v-model="form.specificationModel" type="textarea" :rows="3" placeholder="请输入规格型号" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所属车间">
                            <el-select v-model="form.workshopId" placeholder="请选择所属车间">
                                <el-option
                                    v-for="workshop in workshops"
                                    :key="workshop.value"
                                    :label="workshop.label"
                                    :value="workshop.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20" style="margin-top: 20px;">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改弹窗 -->
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { finddeviceLedger, deletedeviceLedger, updatedeviceLedger, insertdeviceLedger, getspotInspectionfind } from '@/apis/zs';
import { findWorkshop } from '@/apis/zyj/workshop'; // 确保这一行导入是有效的
import { Search, Refresh, Delete, Plus, Edit } from '@element-plus/icons-vue';

// 控制弹窗显示状态
const visible = ref(false);
const title = ref('');
const ids = ref([]);
const deleteDisabled = ref(true);
const pageResult = ref({});
const pageSizes = [2, 5, 8, 10];
const salesorder = ref([]);
const form = ref({
    deviceNo: '',
    deviceName: '',
    deviceTypeId: '',
    workshopId: '',
    brand: '',
    specificationModel: '',
    remark: ''
});
const deviceCategories = ref([]);
const workshops = ref([]);

// 初始化查询参数
const params = ref({
    currentPage: 1,
    pageSize: 5,
    deviceNo: '',
    deviceName: ''
});

// 查询设备数据
const handleSearch = async () => {
    try {
        const response = await finddeviceLedger(params.value);
        pageResult.value = response;
        salesorder.value = response.records; // 更新表格数据
    } catch (error) {
     
    }
};

// 获取设备分类数据
const loadDeviceCategories = async () => {
   
        const response = await getspotInspectionfind();
        deviceCategories.value = response; // 假设你的 API 返回的是数组

};

// 获取车间数据
const loadWorkshops = async () => {
   
        const response = await findWorkshop();
        workshops.value = response; // 假设你的 API 返回的是数组
};

// 显示新增设备弹窗
const insert = () => {
    visible.value = true;
    title.value = '新增设备';
    // 清空表单数据
    form.value = {
        deviceNo: '',
        deviceName: '',
        deviceTypeId: '',
        workshopId: '',
        brand: '',
        specificationModel: '',
        remark: ''
    };
};

// 显示修改设备弹窗
const Update = (row) => {
    visible.value = true;
    title.value = '修改设备';
    form.value = {
        deviceNo: row.deviceNo,
        deviceName: row.deviceName,
        deviceTypeId: row.deviceTypeId,
        workshopId: row.workshopId,
        brand: row.brand,
        specificationModel: row.specificationModel,
        remark: row.remark
    };
};

// 提交表单
const onSubmit = async () => {
    try {
        if (title.value === '新增设备') {
            await insertdeviceLedger(form.value);
        } else if (title.value === '修改设备') {
            await updatedeviceLedger(form.value);
        }
        visible.value = false;
        ElMessage.success(`${title.value}成功`);
        await handleSearch();
    } catch (error) {
        ElMessage.error(`${title.value}失败`);
        console.error(`${title.value}失败:`, error);
    }
};

// 处理选择变化
const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length;
    ids.value = val.map(item => item.deviceNo); // 获取选中行的 ID 数组
};

// 批量删除
const Delete1 = async () => {
    if (ids.value.length === 0) {
        ElMessage.warning('请先选择要删除的项');
        return;
    }

    ElMessageBox.confirm(`是否确认删除访问编号为 ${ids.value.join(',')} 的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deletedeviceLedger(ids.value);
            await handleSearch();
            ids.value = []; // 清空选中的 ID
            ElMessage.success('删除成功');
        } catch (error) {
            ElMessage.error('删除操作失败');
            console.error('删除操作失败:', error);
        }
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

// 关闭弹窗
const handleClose = () => {
    visible.value = false;
};

// 重置查询条件
const paramsReset = () => {
    params.value = {
        currentPage: 1,
        pageSize: 5,
        deviceNo: '',
        deviceName: ''
    };
    handleSearch();
};

// 初始化加载数据
onMounted(async () => {
    await handleSearch();
});
</script>

<style scoped>
.demo-pagination-block {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>
